<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body>
    <!-- 至少有 1 位重复的数字 -->
    <script>
      var found = function (n) {
        if (n < 10) return 0
        const str = n.toString()
        const len = str.length
        let unique = 9
        let p = 2
        let base = 9
        let accu = 9
        while (p < len) {
          accu *= base--
          unique += accu
          p++
        }
        const A = (n, m) => {
          let res = 1
          for (let i = n; i > n - m; i--) {
            res *= i
          }
          return res
        }
        const set = new Set()
        for (let i = 0; i < len; i++) {
          let x = +str[i]
          let small = 0
          for (let j = 0; j < i; j++) {
            if (+str[j] < x) {
              small++
            }
          }
          if (i === 0) {
            unique += (x - 1) * A(9, len - 1)
          } else if (i === len - 1) {
            unique += x - small - (set.has(x) ? 1 : 0) + 1
          } else {
            unique += (x - small) * A(9 - i, len - 1 - i)
          }
          if (set.has(x)) break
          else set.add(x)
        }
        return n - unique
      }
      console.log(found(20))
    </script>
  </body>
</html>
